/**
 * 待我审批
 */
import React, { Fragment, useState, useEffect } from 'react';
import { connect } from 'umi';
import { history } from 'umi'
import { Form, Table, Card, Button } from 'antd';
import xss from 'xss';

import { utils } from 'vv-frontend-components';
import ApplyStatus from '@/components/ApplyStatus';
import PageRouter from '@/components/PageRouter/PageRouter';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Pagination from '@/components/Pagination';
import ProxyModal from '@/pages/Flow/Mine/WaitApproval/NewProxyModal';
import AuthCode from '@/utils/auth/AuthCode';
import AuthComponent from '@/utils/auth/AuthComponent';
import { withRoutePage } from '@/utils/enhanceUtils';
import request from '@/utils/request';
import styles from './index.less';
import { TableAction } from './Action';
import SearchList from './SearchList';

const List = ({ waitApproval, dispatch, loading, applyCommon, route }) => {
    const { waitApprovalPagination: pagination, waitApprovalList: data, action: buttonAction } = waitApproval;
    const user = localStorage.getItem('user');
    const { postId = '' } = user ? JSON.parse(user) : {};
    const { authCode } = new AuthCode(route.code);
    const [advancedSearch, setAdvancedSearch] = useState({});
    const [visible, setVisible] = useState(false);
    const [sysbysomeone, setSysbysomeone] = useState(false); // 是否需要ceo助理审批
    const [sorters, setSorters] = useState(''); // 排序储存
    const { statusPropsList } = applyCommon;

    const handleSubmit = async (values, actionName, extradata) => {
        let result = false;
        switch (actionName) {
            case '审批同意':
                if (values.sysApproveByPresident !== undefined) {
                    const { sysApproveByPresident, ...otherValue } = values;
                    await dispatch({
                        type: 'waitApproval/fetchAgree',
                        payload: {
                            ...otherValue,
                            ...extradata,
                            variableMap: {
                                sys_approveByPresident: values.sysApproveByPresident
                            }
                        },
                        callBack: d => {
                            result = d;
                        }
                    });
                } else if (values.sysApproveByPresidentAssistant !== undefined) {
                    const { sysApproveByPresidentAssistant, ...otherValues } = values;
                    await dispatch({
                        type: 'waitApproval/fetchAgree',
                        payload: {
                            ...otherValues,
                            ...extradata,
                            variableMap: {
                                sys_approveByPresidentAssistant: values.sysApproveByPresidentAssistant
                            }
                        },
                        callBack: d => {
                            result = d;
                        }
                    });
                } else {
                    await dispatch({
                        type: 'waitApproval/fetchAgree',
                        payload: {
                            ...values,
                            ...extradata
                            // variableMap: {
                            //     sys_approveByPresidentAssistant: false
                            // }
                        },
                        callBack: d => {
                            result = d;
                        }
                    });
                }

                break;
            case '审批拒绝':
                await dispatch({
                    type: 'waitApproval/fetchRefuse',
                    payload: {
                        ...values,
                        ...extradata
                    },
                    callBack: d => {
                        result = d;
                    }
                });
                break;
            case '审批退回':
                await dispatch({
                    type: 'waitApproval/fetchReturn',
                    payload: {
                        ...values,
                        ...extradata
                    },
                    callBack: d => {
                        result = d;
                    }
                });
                break;
            default:
                break;
        }
        // 这个地方写你的请求 请求成功返回 true
        return result;
        // setVisible(false);
    };
    const newState = (record, showtype) => {
        const oldStatus = `${record.status}`;
        const newcandidateUsers = record.candidateUsers.split('#');
        let status = '';
        let newUsers = '';
        let statusString = '';
        if (newcandidateUsers.length > 1) {
            newUsers = `${newcandidateUsers.length}人-`;
        } else {
            newUsers = `${record.candidateUsers}-`;
        }
        statusPropsList.forEach(item => {
            if (item.key === oldStatus) {
                status = item.value;
            }
        });
        if (showtype) {
            if (record.candidateUsers === '') {
                statusString = `${status}`;
            } else {
                statusString = `${newUsers}${status}`;
            }
            return statusString;
        }
        return (
            <div>
                <ApplyStatus status={record.status} />
                {record.candidateUsers === '' ? null : newUsers}
                {status}
            </div>
        );
    };
    const fetchWaitApprovalList = Fields => {
        dispatch({
            type: 'waitApproval/fetchWaitApprovalList',
            payload: utils.deepTrim({
                // companyId: userInfo.companyId,
                // postName: searchValue,
                ...Fields,
                pageNo: pagination.current,
                pageSize: pagination.pageSize,
                orderBy: waitApproval.order
            })
        });
    };

    const columns = [
        {
            title: '申请主题',
            dataIndex: 'applicationName',
            key: 'applicationName',
            width: '20%',
            render: (text, record) => (
                <span>
                    <a
                        href="#"
                        onClick={e => {
                            e.preventDefault();
                            const { applicationNo, formDeploymentId } = record;
                            history.push({
                                pathname: '/personal/portal/flow/mine/approvalDetail',
                                query: {
                                    applicationNo,
                                    formDeploymentId
                                }
                            });
                        }}
                    >
                        {text}
                    </a>
                </span>
            )
        },
        {
            title: '申请单摘要',
            dataIndex: 'applicationNote',
            key: 'applicationNote',
            render(text) {
                return (
                    <div
                        style={{
                            display: '-webkit-box',
                            WebkitLineClamp: 5,
                            overflow: 'hidden',
                            maxHeight: 105,
                            WebkitBoxOrient: 'vertical'
                        }}
                    >
                        <span style={{ wordBreak: 'break-all' }} dangerouslySetInnerHTML={{ __html: xss(text) }} />
                    </div>
                );
            }
        },
        {
            title: '发起时间',
            dataIndex: 'startTime',
            key: 'startTime',
            width: 200,
            sorter: () => {}
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'states',
            width: '15%',
            render: (text, record) => newState(record)
        },
        {
            title: '操作',
            width: 160,
            fixed: 'right',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                const extra = {
                    applicationNo: record.applicationNo,
                    processInstanceId: record.processInstanceId,
                    applicationName: record.applicationName,
                    applyId: record.id
                };
                return (
                    <TableAction
                        actionSubmit={handleSubmit}
                        extradata={extra}
                        formKey={record.formKey}
                        postId={postId}
                        sysbysomeone={sysbysomeone}
                        setSysbysomeone={setSysbysomeone}
                    />
                );
            }
        }
    ];

    const handleSearch = Fields => {
        setAdvancedSearch(Fields);
        if (waitApproval.waitApprovalPagination.current !== 1) {
            dispatch({
                type: 'waitApproval/save',
                payload: {
                    waitApprovalPagination: {
                        ...waitApproval.waitApprovalPagination,
                        current: 1
                    }
                }
            });
        } else {
            fetchWaitApprovalList(Fields);
        }
    };

    // 发起时间排序
    const tableChange = (newPagination, filters, sorter) => {
        //    alert(3);
        let sorterField;
        let orderBy;
        if (sorter && sorter.field === 'startTime') {
            sorterField = 'starting_time';
            const order = sorter.order.trim().split('end')[0];
            orderBy = `${sorterField} ${order}`;
        } else if (typeof sorters === 'string') {
            dispatch({
                type: 'waitApproval/save',
                payload: {
                    order: ''
                }
            });
        }
        dispatch({
            type: 'waitApproval/save',
            payload: {
                order: orderBy || '',
                waitApprovalPagination: {
                    ...waitApproval.waitApprovalPagination,
                    ...newPagination
                }
            }
        });
        if (sorter && sorters !== sorter) {
            setSorters(sorter);
            dispatch({
                type: 'waitApproval/save',
                payload: {
                    order: orderBy || '',
                    waitApprovalPagination: {
                        ...waitApproval.waitApprovalPagination,
                        current: 1
                    }
                }
            });
        }
    };

    useEffect(() => {
        const fetchCeoAssistant = async () => {
            // 当前登录用户为区域CEO时才请求是否存在CEO助理
            if ([148, 173].includes(postId)) {
                // 请求是否有ceo助理
                const response = await request('/api/oa/v1/post/getemployeebypostidbyprocess/251');
                if (response.code === 10000) {
                    setSysbysomeone(true);
                } else {
                    setSysbysomeone(false);
                }
            }
        };
        fetchCeoAssistant();
    }, []);
    // 每当分页数或页数改变时均应该重新请求表格数据
    useEffect(() => {
        fetchWaitApprovalList(advancedSearch);
    }, [waitApproval.order, pagination.pageSize, pagination.current, buttonAction]);
    useEffect(
        () => () => {
            dispatch({
                type: 'waitApproval/save',
                payload: {
                    order: '',
                    action: '',
                    waitApprovalPagination: {
                        current: 1,
                        pageSize: 10
                    }
                }
            });
        },
        []
    );
    const extraButton = (
        <AuthComponent code={authCode('proxy')}>
            <Button type="primary" onClick={() => setVisible(true)}>
                流程代理设置
            </Button>
        </AuthComponent>
    );
    return (
        <PageHeaderWrapper>
            <PageRouter type="myflow" extraButton={extraButton}>
                {isPageRouter => (
                    <Fragment>
                        <Card
                            bordered={false}
                            title={!isPageRouter && '待我审批'}
                            className={styles.tableapproval}
                            extra={!isPageRouter && extraButton}
                        >
                            <SearchList onSearch={handleSearch} />
                            <Table
                                bordered={false}
                                columns={columns}
                                loading={loading}
                                dataSource={data}
                                onChange={tableChange}
                                rowKey="id"
                                pagination={false}
                                scroll={{ x: 'max-content' }}
                            />
                            <Pagination {...pagination} onChange={tableChange} />
                        </Card>
                        <ProxyModal
                            visible={visible}
                            onOk={() => setVisible(false)}
                            onCancel={() => setVisible(false)}
                            width={900}
                        />
                    </Fragment>
                )}
            </PageRouter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ loading, waitApproval, applyCommon }) => ({
        waitApproval,
        applyCommon,
        loading: loading.models.waitApproval
    }))(Form.create()(List))
);
